package com.xteam.ecsystem.utils;

import java.io.OutputStream;
import java.util.List;

import com.xteam.ecsystem.dao.initialXlsColumnDao;
import com.xteam.ecsystem.dao.Impl.initOrderXlsColumnDaoImpl;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@SuppressWarnings("unchecked")
public class ReadOrCreateXLS {

	public static initialXlsColumnDao getColumnInstence(String str) {
		
		if ("order".equals(str)) {
			return new initOrderXlsColumnDaoImpl();
		}
		
		if ("product".equals(str)) {
			return new initOrderXlsColumnDaoImpl();
		}
		
		return null;
	}

	public static void setColumnList(WritableSheet wsheet, int[] widthList) {
		if (widthList != null) {
			for (int i = 0; i < widthList.length; i++) {
				wsheet.setColumnView(i, widthList[i]);
			}
		}
	}

	public static void exportExcel(OutputStream os, List list, String[] title,
			String SheetName, int[] widthList, String factoryName) {
		try {
			WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
			WritableSheet wsheet = wbook.createSheet(SheetName, 0); // sheet名称
			// 设置excel标题
			WritableFont wfont = new WritableFont(WritableFont.ARIAL, 12,
					WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.WHITE);
			WritableCellFormat wcfFC = new WritableCellFormat(wfont);
			wcfFC.setBackground(Colour.BLUE_GREY);
			setColumnList(wsheet, widthList);
			for (int i = 0; i < title.length; i++) {
				wsheet.addCell(new Label(i, 0, title[i], wcfFC));
			}
			wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10,
					WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLACK);
			wcfFC = new WritableCellFormat(wfont);
			initialXlsColumnDao initialXlsColumndao = getColumnInstence(factoryName);
			initialXlsColumndao.setCellList(list, wsheet, wcfFC);
			wbook.write(); // 写入文件
			wbook.close();
			os.flush();
			os.close(); // 关闭流
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
